<?php

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/3/6
 * Time: 15:29
 */
namespace Admin\Model;

use Think\Image;
use Think\Model,Think\Upload;

class GoodsModel extends Model{
    protected $tablename = 'goods';

    protected $insertFields = 'goods_name,market_price,shop_price,goods_desc,is_onsale,brand_id,cat_id,type_id,goods_number,promote_price,promote_start_date,promote_end_date,is_new,is_best,is_hot,sort_num,is_floor';

    protected $updateFields = 'id,is_onsale,goods_name,market_price,shop_price,goods_desc,brand_id,cat_id,type_id,goods_number,promote_price,promote_start_date,promote_end_date,is_new,is_best,is_hot,sort_num,is_floor';

    protected $_validate = array(
        array('cat_id','require','必须选择主分类！',1),
        array('goods_name','require','商品名称不能为空！',1),
        array('market_price','currency','市场价格不能为空',1),
        array('shop_price','currency','本店价格不能为空',1),
    );
    protected $_auto = array(array('addtime','getDate',1,'callback'));

    public function getDate(){
        return date('Y-m-d H:i:s',NOW_TIME);
    }
    /**************搜索与分页******************/
    public function search($perPage = 10){
        $where = array();
        $count = $this->where($where)->count();
        $pageObj = new \Think\Page($count,$perPage);
        $pageObj->setConfig('next','下一页');
        $pageObj->setConfig('prev','上一页');
        $pageString = $pageObj->show();
        $orderby = 'a.id';
        $orderway = 'desc';
        $odby = I('get.odby');
        if($odby) {
            if ($odby == 'id_asc') {
                $orderway = 'asc';
            } elseif ($odby == 'price_desc') {
                $orderby = 'shop_price';
            } elseif ($odby == 'price_asc') {
                $orderby = 'shop_price';
                $orderway = 'asc';
            }
        }


        $gn = I('get.gn');
        if($gn){
            $where['a.goods_name'] = array('like',"%{$gn}%");
        }

        $fp = I('get.fp');
        $tp = I('get.tp');
        if($fp && $tp){
            $where['a.shop_price'] = array('between',array($fp,$tp));
        } elseif($fp) {
            $where['a.shop_price'] = array('egt',$fp);
        } elseif($tp){
            $where['a.shop_price'] = array('elt',$tp);
        }

        $ios = I('get.ios');
        if($ios != null && ($ios || $ios == 0) ){
            $where['a.is_onsale'] = array('eq',$ios);
        }
        $fa = I('get.fa');
        $ta = I('get.ta');
        if($fa && $ta){
            $where['a.addtime'] = array('between',array($fa,$ta));
        } elseif($fa) {
            $where['a.addtime'] = array('egt',$fa);
        } elseif($ta) {
            $where['a.addtime'] = array('elt',$ta);
        }
        /**品牌搜索**/
        $brandId = I('get.brand_id');
        if($brandId){
            $where['a.brand_id'] = array('eq',$brandId);
        }
        /**分类搜索**/
        $catId = I('get.cat_id');
        if($catId){
            $gids = $this->getGoodsIdByCatId($catId);
            $where['a.id'] = array('IN',$gids);
        }
        $data = $this->order("$orderby $orderway")
            ->field('a.*,b.brand_name,c.cat_name,GROUP_CONCAT(e.cat_name SEPARATOR "<br/>") ext_cat_name')
            ->alias('a')
            ->join('LEFT JOIN __BRAND__ b ON a.brand_id = b.id
                    LEFT JOIN __CATEGORY__ c ON a.cat_id = c.id
                    LEFT JOIN __GOODS_CAT__ d ON a.id = d.goods_id
                    LEFT JOIN __CATEGORY__ e ON d.cat_id = e.id')
            ->where($where)
            ->limit($pageObj->firstRow.','.$pageObj->listRows)
            ->group('a.id')
            ->select();
        return array(
            'data' => $data,
            'page' => $pageString,
        );
    }
    /**************添加之前******************/
    protected function _before_insert(&$data,$option){

        if($_FILES['logo']['error'] == 0) {
            $ret = uploadOne('logo','Goods',array(
                array(700,700),
                array(350,350),
                array(130,130),
                array(50,50),
            ));
            $data['logo'] = $ret['images'][0];
            $data['mbig_logo'] =$ret['images'][1];
            $data['big_logo'] = $ret['images'][2];
            $data['mid_logo'] = $ret['images'][3];
            $data['sm_logo'] = $ret['images'][4];
        }
//var_dump($data);exit;
        if(!$data['promote_start_date'])
            unset($data['promote_start_date']);
        if(!$data['promote_end_date'])
            unset($data['promote_end_date']);
        //var_dump($data);exit;

        $data['goods_desc'] = removeXss($_POST['goods_desc']);
    }
    /**************更新之前******************/
    public function _before_update(&$data,$option)
    {
        $id = $option['where']['id'];

        if(!$data['promote_start_date'])
            unset($data['promote_start_date']);
        if(!$data['promote_end_date'])
            unset($data['promote_end_date']);

        /**处理扩展分类**/
        $ecid = I('post.ext_cat_id');
        $gcModel = D('goods_cat');
        $gcModel->where(array(
            'goods_id' => array('eq',$id),
        ))->delete();
        if($ecid){
            foreach($ecid as $k=>$v){
                if(empty($v)){
                    continue;
                }
                $gcModel->add(array(
                    'cat_id' => $v,
                    'goods_id' => $id,
                ));
            }
        }

        /**************LOGO上传******************/
        if ($_FILES['logo']['error'] == 0) {
            $upload = new Upload();
            $upload->maxSize = 1024 * 1024;
            $upload->exts = array('jpg', 'gif', 'png', 'jpeg');
            $upload->rootPath = './Public/Uploads/';
            $upload->savePath = 'Goods/';
            $info = $upload->upload();
            if (!$info) {
                $this->error = $upload->getError();
                return false;
            } else {
                $logo = $info['logo']['savepath'] . $info['logo']['savename'];
                $mbig_logo = $info['logo']['savepath'] . 'mbig_' . $info['logo']['savename'];
                $big_logo = $info['logo']['savepath'] . 'big_' . $info['logo']['savename'];
                $mid_logo = $info['logo']['savepath'] . 'mid_' . $info['logo']['savename'];
                $sm_logo = $info['logo']['savepath'] . 'sm_' . $info['logo']['savename'];
                $image = new Image();
                $image->open('./Public/Uploads/' . $logo);
                //生成缩略图
                $image->thumb(700, 700)->save('./Public/Uploads/' . $mbig_logo);
                $image->thumb(350, 350)->save('./Public/Uploads/' . $big_logo);
                $image->thumb(130, 130)->save('./Public/Uploads/' . $mid_logo);
                $image->thumb(50, 50)->save('./Public/Uploads/' . $sm_logo);
                $data['logo'] = $logo;
                $data['mbig_logo'] = $mbig_logo;
                $data['big_logo'] = $big_logo;
                $data['mid_logo'] = $mid_logo;
                $data['sm_logo'] = $sm_logo;
                $oldLogo = $this->field('logo,mbig_logo,big_logo,mid_logo,sm_logo')->find($id);
                unlink('./Public/Uploads/' . $oldLogo['logo']);
                unlink('./Public/Uploads/' . $oldLogo['mbig_logo']);
                unlink('./Public/Uploads/' . $oldLogo['big_logo']);
                unlink('./Public/Uploads/' . $oldLogo['mid_logo']);
                unlink('./Public/Uploads/' . $oldLogo['sm_logo']);

            }
        }


        /**************相册上传******************/
        if(isset($_FILES['pic'])){
            $pics = array();
            foreach ($_FILES['pic']['name'] as $k=>$v){
                $pics[] = array(
                    'name' => $v,
                    'type' => $_FILES['pic']['type'][$k],
                    'tmp_name' => $_FILES['pic']['tmp_name'][$k],
                    'error' => $_FILES['pic']['error'][$k],
                    'size' => $_FILES['pic']['size'][$k],
                );
            }
            $_FILES = $pics;
            $gpModel = D('goods_pic');
            foreach($pics as $k=>$v){
                if($v['error'] == 0){
                    $ret = uploadOne($k,'Goods',array(
                        array(650,650),
                        array(350,350),
                        array(50,50),
                    ));
                    if($ret['ok'] == 1){
                        $gpModel->add(array(
                            'pic' => $ret['images'][0],
                            'big_pic' => $ret['images'][1],
                            'mid_pic' => $ret['images'][2],
                            'sm_pic' => $ret['images'][3],
                            'goods_id' => $id,

                        ));
                    }
                }
            }

        }
        /**修改会员价格**/
        $mp = I('post.member_price');
        $mpModel = D('member_price');
        $mpModel->where(array(
            'goods_id' => array('eq',$id),
        ))->delete();
        foreach ($mp as $k=>$v){
            $_v = (float)$v;
            if($_v > 0){
                $mpModel->add(array(
                    'price' => $_v,
                    'level_id' => $k,
                    'goods_id' => $id,
                ));
            }
        }

        /**修改商品属性**/
        $gaid = I('post.goods_attr_id');
        $attrValue = I('post.attr_value');
        $gaModel = D('goods_attr');
        $_i = 0;
        foreach ($attrValue as $k => $v){
            foreach ($v as $k1 => $v1){
                if($gaid[$_i] == ''){
                    $gaModel->add(array(
                        'goods_id' => $id,
                        'attr_id' => $k,
                        'attr_value' => $v1,
                    ));
                    } else {
                        $gaModel->where(array(
                            'id' => array('eq',$gaid[$_i]),
                        ))->setField('attr_value',$v1);
                }
                $_i++;
            }
        }

        $data['goods_desc'] = removeXss($_POST['goods_desc']);
    }
    /**************删除之前******************/
    public function _before_delete($option){
        $id = $option['where']['id'];

        /**删除商品扩展分类**/
        $gcModel = D('goods_cat');
        $gcModel->where(array(
           'goods_id' => $id,
        ))->delete();

        /**删除商品相册**/
        $gpModel = D('goods_pic');
        $pics = $gpModel->field('pic,sm_pic,mid_pic,big_pic')->where(array(
            'goods_id' => array('eq',$id),
        ))->select();
        foreach($pics as $k=>$v)
            deleteImage($v);
        $gpModel->where(array(
            'goods_id' => array('eq',$id),
        ))->delete();

        /**删除商品LOGO**/
        $oldLogo = $this->field('logo,mbig_logo,big_logo,mid_logo,sm_logo')->find($id);
        deleteImage($oldLogo);
        $mpModel = D('member_price');
        $mpModel->where(array(
            'goods_id' => array('eq',$id),
        ))->delete();

        /**删除商品属性**/
        $gaModel = D('goods_attr');
        $gaModel->where(array(
            'goods_id' => array('eq',$id),
        ))->delete();
    }
    /**************添加之后******************/
    public function _after_insert($data,$option){
        /**处理扩展分类**/
        $ecid = I('post.ext_cat_id');
        if($ecid){
            $gcModel = D('goods_cat');
            foreach($ecid as $k=>$v){
                if(empty($v))
                    continue;
                $gcModel->add(array(
                   'cat_id' => $v,
                    'goods_id' => $data['id'],
                ));
            }
        }

        /**处理相册图片**/
        if(isset($_FILES['pic'])){
            $pics = array();
            foreach ($_FILES['pic']['name'] as $k=>$v){
                $pics[] = array(
                    'name' => $v,
                    'type' => $_FILES['pic']['type'][$k],
                    'tmp_name' => $_FILES['pic']['tmp_name'][$k],
                    'error' => $_FILES['pic']['error'][$k],
                    'size' => $_FILES['pic']['size'][$k],
                );
            }
            $_FILES = $pics;
            $gpModel = D('goods_pic');
            foreach($pics as $k=>$v){
                if($v['error'] == 0){
                    $ret = uploadOne($k,'Goods',array(
                        array(650,650),
                        array(350,350),
                        array(50,50),
                    ));
                    if($ret['ok'] == 1){
                        $gpModel->add(array(
                            'pic' => $ret['images'][0],
                            'big_pic' => $ret['images'][1],
                            'mid_pic' => $ret['images'][2],
                            'sm_pic' => $ret['images'][3],
                            'goods_id' => $data['id'],

                        ));
                    }
                }
            }

        }

        /**处理会员价格**/
        $mp = I('post.member_price');
        $mpModel = D('member_price');
        foreach ($mp as $k=>$v){
            $_v = (float)$v;
            if($_v > 0){
                $mpModel->add(array(
                    'price'=>$_v,
                    'level_id'=>$k,
                    'goods_id'=>$data['id'],
                ));
            }
        }

        /**处理商品属性**/
        $attrValue = I('post.attr_value');
        $gaModel = D('goods_attr');
        foreach($attrValue as $k=>$v){
            $v = array_unique($v);
            foreach ($v as $k1=>$v1) {
                if($v1 != ''){
                    $gaModel->add(array(
                        'goods_id' => $data['id'],
                        'attr_id' => $k,
                        'attr_value' => $v1,

                    ));
                }
            }
        }
    }

    public function getGoodsIdByCatId($catId){
        $catModel = D('Admin/Category');
        $children = $catModel->getChildren($catId);
        $children[] = $catId;
        /**取出主分类下的商品ID**/
        $gids = $this->field('id')->where(array(
            'cat_id' => array('IN',$children),
        ))->select();//var_dump($gids);exit;
        /**取出扩展分类下的商品ID**/
        $gcModel = D('goods_cat');
        $gids1 = $gcModel->field('DISTINCT goods_id id')->where(array(
            'cat_id' => array('IN',$children)
        ))->select();
        if($gids && $gids1){
            $gids = array_merge($gids,$gids1);
        } elseif($gids1) {
            $gids = $gids1;
        }
        $id = array();
        foreach ($gids as $k=>$v){
            if(!in_array($v['id'],$id)){
                $id[] = $v['id'];
            }
        }
        return $id;
    }
    /**取出当前正在促销的商品**/
    public function getPromoteGoods($limit = 5){
        $today = date('Y-m-d H:i');
        return $this->field('id,goods_name,mid_logo,promote_price')
                    ->where(array(
                        'is_onsale' => array('eq',1),
                        'promote_price' => array('gt',0),
                        'promote_start_date' => array('elt',$today),
                        'promote_end_date' => array('egt',$today),
                    ))->limit($limit)
                      ->order('sort_num ASC')
                      ->select();
    }

    /**取出三种推荐商品的数据**/
    public function getRecGoods($recType,$limit = 5){
        return $this->field('id,goods_name,mid_logo,shop_price')
                    ->where(array(
                        'is_onsale' => array('eq',1),
                        "$recType" => array('eq','是'),
                    ))->limit($limit)->order('sort_num ASC')->select();
    }

    /**获取会员价格**/
    public function getMemberPrice($goodsId){
        $today = date('Y-m-d H:i');
        $levelId = session('level_id');
        //取出商品促销价格
        $promotePrice = $this->field('promote_price')->where(array(
            'id' => array('eq',$goodsId),
            'promote_price' => array('gt',0),
            'promote_start_date' => array('elt',$today),
            'promote_end_date' => array('egt',$today),
        ))->find();
        //判断会员是否登录
        if($levelId){
            $mpModel = D('Admin/member_price');
            $mpData = $mpModel->field('price')->where(array(
                'goods_id' => array('eq',$goodsId),
                'level_id' => array('eq',$levelId),
            ))->find();

            if($mpData['price']){
                if($promotePrice['promote_price']){
                    return min($promotePrice['promote_price'],$mpData['price']);
                } else {
                    return $mpData['price'];
                }
            } else {
                $p = $this->field('sp_price')->field($goodsId);
                if($promotePrice['promote_price']){
                    return min($promotePrice['promote_price'],$p['shop_price']);
                } else {
                    return $p['shop_price'];
                }
            }
        } else {
            $p = $this->field('shop_price')->find($goodsId);
            if($promotePrice['promote_price']){
                return min($promotePrice['promote_price'],$p['shop_price']);
            } else {
                return $p['shop_price'];
            }
        }
    }

    public function cat_search($catId,$pageSize=12){
        //根据分类ID搜索出这个分类下商品的ID
        $goodsId = $this->getGoodsIdByCatId($catId);
        !$goodsId && $goodsId = array(0);
        $where['a.id'] = array('in',$goodsId);
        //品牌
        $brandId = I('get.brand_id');
        if($brandId){
            $where['a.brand_id'] = array('eq',(int)$brandId);
        }
        //价格
        $price = I('get.price');
        if($price){
            $price = explode('-',$price);
            $where['a.shop_price'] = array('between',$price);
        }
        /****************商品搜索开始*******************/
        $gaModel = D('GoodsAttr');
        $attrGoodsId = null; //根据每个属性搜素出来的商品ID
        //根据属性搜索：循环所有参数找出属性的参数进行查询
        foreach($_GET as $k => $v){
            //如果变量是已attr_开头的说明是一个属性的查询，格式：attr_1/黑色-颜色
            if(strpos($k,'attr_') ===0){
                //先解析出属性ID和属性值
                $attrId = str_replace('attr_','',$k); //属性ID
                //先取出最后一个 '-' 往后的字符串
                $attrName = strrchr($v,'-');
                $attrValue = str_replace($attrName,'',$v);
                //根据属性ID和属性值搜索出这个属性值下的商品ID，并返回一个字符串格式：1，2，3，4，5
                $gids = $gaModel->field('GROUP_CONCAT(goods_id) gids')->where(array(
                    'attr_id' => array('eq',$attrId),
                    'attr_value' => array('eq',$attrValue),
                ))->find();

                //判断是否有商品
                if($gids['gids']){
                    $gids['gids'] = explode(',',$gids['gids']);
                    //说明是搜索的第一个属性
                    if($attrGoodsId === null){
                        $attrGoodsId = $gids['gids']; //暂存起来
                    } else {
                        $attrGoodsId = array_intersect($attrGoodsId,$gids['gids']);
                        //如果已经没有商品满足条件就不用再考虑下一个属性
                        if(empty($attrGoodsId)){
                            $where['a.id'] = array('eq',0);
                            break;
                        }
                    }
                } else {
                    //前几次的交集结果清空
                    $attrGoodsId = array();
                    //如果这个属性下没有商品就应该向where中添加一个不可能满足的条件，这样后面取商品时就取不出来了
                    $where['a.id'] = array('eq',0);
                    //取出循环,不用再查询下一个属性
                    break;
                }
            }
        }
        //判断如果循环求次之后这个数组还不为空说明这些就是满足所有条件的商品ID
        if($attrGoodsId){
            $where['a.id'] = array('in',$attrGoodsId);
        }
        /******************商品搜索结束*************************/

        /********************翻页**************************/
        //取出总的记录数，以及所有商品ID的字符串
        $count = $this->alias('a')
            ->field('COUNT(a.id) goods_count,GROUP_CONCAT(a.id) goods_id')
            ->where($where)->find();
        //把商品ID返回

        $data['goods_id'] = explode(',',$count['goods_id']);
        $page = new \Think\Page($count['goods_count'],$pageSize);
        //配置翻页样式
        $page->setConfig('prev','上一页');
        $page->setConfig('next','下一页');
        $data['page'] = $page->show();
        /********************排序*************************/
        $oderby = 'xl'; //默认
        $orderway = 'desc'; //默认
        $odby = I('get.odby');
        if($odby){
            if($odby == 'addtime'){
                $oderby = 'a.addtime';
            }
            if(strpos($odby,'price_') === 0){
                $oderby = 'a.shop_price';
                if($odby == 'price_asc'){
                    $oderway = 'desc';
                }
            }
        }

        /********************取数据***********************/
        $data['data'] = $this->alias('a')
            ->field('a.id,a.goods_name,a.mid_logo,a.shop_price,SUM(b.goods_number) xl')
            ->join('LEFT JOIN __ORDER_GOODS__ b ON a.id=b.goods_id AND b.order_id IN(SELECT id FROM __ORDER__ WHERE pay_status="是")')
            ->where($where)
            ->group('a.id')
            ->limit($page->firstRow.','.$page->listRows)
            ->order("$oderby $oderway")
            ->select();
        return $data;
    }

    /*********************获取某个关键字下某一项商品********************************/
    public function key_search($key,$pageSize=60){
        //根据关键字【商品名称、商品描述、商品属性值】取出商品ID
        $goodsId = $this->alias('a')
            ->field('GROUP_CONCAT(DISTINCT a.id) gids')
            ->join('LEFT JOIN __GOODS_ATTR__ b ON a.id=b.goods_id')
            ->where(array(
                'a.is_onsale' => array('eq',1),
                'a.goods_name' => array('exp',"LIKE '%$key%' OR a.goods_desc LIKE '%$key%' OR b.attr_value LIKE  '%$key%'"),
            ))->find();
        $goodsId = explode(',',$goodsId['gids']);
        $where['a.id'] = array('in',$goodsId);
        //品牌
        $brandId = I('get.brand_id');
        if($brandId){
            $where['a.brand_id'] = array('eq',(int)$brandId);
        }
        //价格
        $price = I('get.price');
        if($price){
            $price = explode('-',$price);
            $where['a.shop_price'] = array('between',$price);
        }
        /****************商品搜索开始*******************/
        $gaModel = D('GoodsAttr');
        $attrGoodsId = null; //根据每个属性搜素出来的商品ID
        //根据属性搜索：循环所有参数找出属性的参数进行查询
        foreach($_GET as $k => $v){
            //如果变量是已attr_开头的说明是一个属性的查询，格式：attr_1/黑色-颜色
            if(strpos($k,'attr_') ===0){
                //先解析出属性ID和属性值
                $attrId = str_replace('attr_','',$k); //属性ID
                //先取出最后一个 '-' 往后的字符串
                $attrName = strrchr($v,'-');
                $attrValue = str_replace($attrName,'',$v);
                //根据属性ID和属性值搜索出这个属性值下的商品ID，并返回一个字符串格式：1，2，3，4，5
                $gids = $gaModel->field('GROUP_CONCAT(goods_id) gids')->where(array(
                    'attr_id' => array('eq',$attrId),
                    'attr_value' => array('eq',$attrValue),
                ))->find();

                //判断是否有商品
                if($gids['gids']){
                    $gids['gids'] = explode(',',$gids['gids']);
                    //说明是搜索的第一个属性
                    if($attrGoodsId === null){
                        $attrGoodsId = $gids['gids']; //暂存起来
                    } else {
                        $attrGoodsId = array_intersect($attrGoodsId,$gids['gids']);
                        //如果已经没有商品满足条件就不用再考虑下一个属性
                        if(empty($attrGoodsId)){
                            $where['a.id'] = array('eq',0);
                            break;
                        }
                    }
                } else {
                    //前几次的交集结果清空
                    $attrGoodsId = array();
                    //如果这个属性下没有商品就应该向where中添加一个不可能满足的条件，这样后面取商品时就取不出来了
                    $where['a.id'] = array('eq',0);
                    //取出循环,不用再查询下一个属性
                    break;
                }
            }
        }
        //判断如果循环求次之后这个数组还不为空说明这些就是满足所有条件的商品ID
        if($attrGoodsId){
            $where['a.id'] = array('in',$attrGoodsId);
        }
        /******************商品搜索结束*************************/

        /********************翻页**************************/
        //取出总的记录数，以及所有商品ID的字符串
        $count = $this->alias('a')
            ->field('COUNT(a.id) goods_count,GROUP_CONCAT(a.id) goods_id')
            ->where($where)->find();
        //把商品ID返回

        $data['goods_id'] = explode(',',$count['goods_id']);
        $page = new \Think\Page($count['goods_count'],$pageSize);
        //配置翻页样式
        $page->setConfig('prev','上一页');
        $page->setConfig('next','下一页');
        $data['page'] = $page->show();
        /********************排序*************************/
        $oderby = 'xl'; //默认
        $orderway = 'desc'; //默认
        $odby = I('get.odby');
        if($odby){
            if($odby == 'addtime'){
                $oderby = 'a.addtime';
            }
            if(strpos($odby,'price_') === 0){
                $oderby = 'a.shop_price';
                if($odby == 'price_asc'){
                    $oderway = 'desc';
                }
            }
        }

        /********************取数据***********************/
        $data['data'] = $this->alias('a')
            ->field('a.id,a.goods_name,a.mid_logo,a.shop_price,SUM(b.goods_number) xl')
            ->join('LEFT JOIN __ORDER_GOODS__ b ON a.id=b.goods_id AND b.order_id IN(SELECT id FROM __ORDER__ WHERE pay_status="是")')
            ->where($where)
            ->group('a.id')
            ->limit($page->firstRow.','.$page->listRows)
            ->order("$oderby $oderway")
            ->select();
        return $data;
    }

}